import compose from './compose';

// // 单个中间件
// export function applyMiddleware(middleware) {
//   return createStore => (...args) => {
//     const store = createStore(...args);
//     let dispatch = store.dispatch;

//     const midApi = {
//       getState: store.getState,
//       dispatch: (...arg) => dispatch(...arg)
//     }

//     dispatch = middleware(midApi)(store.dispatch);

//     // 返回原本的store和增的dispatch
//     return {
//       ...store,
//       dispatch
//     }
//   }
// }

// 多个中间件
export default function applyMiddleware(...middlewares) {
  return (createStore) => {
    // args => reducer 和 preloadedState
    return (...args) => {
      const store = createStore(...args);
      let dispatch = store.dispatch;

      // middApi 其实就是中间件第一层（store）的入参
      const middApi = {
        getState: store.getState(),
        dispatch: (...args) => dispatch(...args),
      };

      // 对每个middleware都传入middApi，进行调用，初始化中间件
      // 初始化后的中间件返回一个新的函数，接受store.dispatch作为参数，
      // 返回一个新的dispatch来替换store.dispatch(即增强的dispatch)
      const chin = middlewares.map((middleware) => middleware(middApi));
      // compose方法吧所有中间件都串联起来，最终结果替换dispatch函数
      dispatch = compose(...chin)(store.dispatch);

      // 返回原本的store和增的dispatch
      return {
        ...store,
        dispatch, // 增强后的dispatch
      };

      /**
       * 中间件的形式
       * const middleware = ({getState, dispatch}) => next => action => {
       *    return next(action)
       * }
       * 这里的next是经过上一个中间件处理的dispatch方法
       * next(action) 返回的还是一个dispatch方法
       */
    };
  };
}
